/**
 * Constantes 
 */
var CHECK_STATUS_INTERVAL = 1000; // MILLISECONDS
var TASK_STATUS = ['','En Ejecución','Finalizada','Cancelada','Terminada con Error'];

$(document).ready( function() {
    $('#avancedOptions').accordion({
        collapsible: true
    });
    onLayerChange($('#layer option:selected').text()); // para llenar el combo al principio
    // onchange capa
    $('#layer').change(function(e){
        onLayerChange($(this).children('option:selected').text());
    });
    $('#grid').change(function(e){
        onGridChange($(this).children('option:selected'));
    });
    $('#minZoomLevel').change(function(e){
        fillMaxZoomLevels();
    });
    // solo se puede eligir o nTreads o nProcess 
    $('#nProcess').change(function(){
        if ($(this).val() != 0){
            $('#nThreads').val(0);
        }
    });
    $('#nThreads').change(function(){
        if ($(this).val() != 0){ // si no es el valor inicial
            $('#nProcess').val(0);
        }
    });
    
    $('#task_table').jqGrid(
    {
        datatype : 'local',
        data: {},
        height: '150px',
        rowNum: 10,
        colNames: ['ID', 'PID' , 'Capa' , 'Estado' , 'Inicio','Teselas Procesadas', 'Fin', 'Detener','Check','IntervalID'],
        colModel:[
        {
            name:'taskID', 
            width:50,
            hidden:true
        },
        {
            name:'pid',
            hidden:true,
            width:50,
            align:"center",
            sortable: false
                   
        },

        {
            name:'layer', 
            width:100,
            align:"left",
            sortable: false
                    
        },

        {
            name:'status', 
            width:100, 
            align:"center",
            sortable: false
        },
                
        {
            name:'startDate', 
            width:120, 
            align:"center",
            sortable: false
        },
        {
            name:'tilesProcessed', 
            width:110, 
            align:"center",
            sortable: false
        },
        {
            name:'endDate', 
            width:120, 
            align:"center",
            sortable: false
        }
        ,
        {
            name:'stop', 
            width:65, 
            align:"center",
            sortable: false
        },
        {
            name:'refresh', 
            width:80, 
            hidden:true,
            align:"center",
            sortable: false
        },
        {
            name:'intervalID', 
            width:80, 
            align:"center",
            hidden:true,
            sortable: false
        }
        ],
        caption: "Tareas",
        cellsubmit: 'clientArray',
        gridview: true,
        pager: '#pager'
                
    });
         
});

$(document).ready(function(){
    $('#exec').button();
    $('#exec').click(function(){
        
        if(validate()) {
            $.ajax({
                url: APPALIAS+'/adminLayer/perform',
                type:'POST',
                data: {
                    'layer' : $('#layer option:selected').text().trim(),
                    'grid' :  $('#grid option:selected').text().trim(),
                    'nThreads': $('#nThreads option:selected').text(),
                    'nProcess': $('#nProcess option:selected').text(),
                    'operation': $('#operation option:selected').text(),
                    'metatileX': $('#metatileX option:selected').text(),
                    'metatileY': $('#metatileY option:selected').text(),
                    'minZoomLevel': $('#minZoomLevel option:selected').text(),
                    'maxZoomLevel' : $('#maxZoomLevel option:selected').text(),
                    'bboxMinX' :$('#bboxMinX').val(),
                    'bboxMaxX' :$('#bboxMaxX').val() ,
                    'bboxMinY' :$('#bboxMinY').val(),
                    'bboxMaxY' : $('#bboxMaxY').val()
                },
                dataType: 'json',
                success: function(task){
                    if(task) {
                        // llamo a 
                        var intervalID = window.setInterval(function(){
                            checkStatus(task.taskID,task.pid,task.layer);
                        }, CHECK_STATUS_INTERVAL);
                        var taskObject = {
                            taskID : task.taskID,
                            pid: task.pid,
                            layer: task.layer,
                            status: TASK_STATUS[task.status],
                            startDate: task.startDate,
                            tilesProcessed: task.tilesProcessed,
                            endDate: task.endDate,
                            refresh:'<button onclick="checkStatus('+task.taskID+','+task.pid+','+'\''+task.layer+'\''+');">ver estado</button>',
                            stop:'<button onclick="stopTask('+task.taskID+','+task.pid+');">detener</button>',
                            intervalID: intervalID
                        };
                        var records = $('#task_table').jqGrid('getGridParam', 'records');
                        $('#task_table').addRowData(records +1 , taskObject);
                    
                    }
                    else  {
                        alert('Ya existe una tarea para la capa'); 
                    }
                } // End of success function of ajax form
            }); // End of ajax call  
        }
        else {
            
            alert('Error al ejecutar la tarea, los valores de algunos parámetros no son validos.'); 
        }
    })
    
});
function validate() {
    return validateBbox();
}
function validateBbox() {
    var srs = $('#grid option:selected').text().trim(),
    bboxMinX = $('#bboxMinX').val().trim(),
    bboxMaxX = $('#bboxMaxX').val().trim() ,
    bboxMinY = $('#bboxMinY').val().trim(),
    bboxMaxY = $('#bboxMaxY').val().trim();
    if(bboxMinX + bboxMaxX + bboxMinY + bboxMaxY  == ''){
        return true;
    }
    else {
        var valid = false;
        $.ajax({
            url: APPALIAS+'/adminLayer/getGridData/'+encodeURIComponent(srs),
            type:'GET',
            dataType: 'json',
            async: false,
            success: function(data){
                var gridData = data.grid;
                if (gridData.extent) {
                    valid = bboxMinX >= gridData.extent.minX
                    && bboxMaxX <= gridData.extent.maxX
                    && bboxMinY >= gridData.extent.minY
                    && bboxMaxY <= gridData.extent.maxY
                }
                
            }                       
                        
        });
        return valid;
    // End of success function of ajax form
    }
}


function  checkStatus(taskID,pid,layer) {
    $.ajax({
        url: APPALIAS+'/adminLayer/checkStatus/'+taskID+'/'+pid+'/'+layer,
        type:'GET',
        dataType: 'json',
        success: function(task){
            var grid = $('#task_table');
            var taskID = task.taskID;
            var rowID = findRowIDByTaskID(taskID);
            if(rowID) {
                var rowData = grid.jqGrid('getRowData', rowID);
                grid.jqGrid('setCell', rowID, 'status', TASK_STATUS[task.status]);
                grid.jqGrid('getLocalRow', rowID).status = TASK_STATUS[task.status];  
                 
                grid.jqGrid('setCell', rowID, 'tilesProcessed', task.tilesProcessed);
                grid.jqGrid('getLocalRow', rowID).tilesProcessed = task.tilesProcessed;
                 
                grid.jqGrid('setCell', rowID, 'endDate', task.endDate);
                grid.jqGrid('getLocalRow', rowID).endDate = task.endDate;
                if(task.status != 1) {
                    clearInterval(rowData.intervalID);
                }
            }                       
                        
        } // End of success function of ajax form
    });
}

function findRowIDByTaskID(taskID) {
    var grid_ids= $('#task_table').getDataIDs();
    //Busco la fila
    for(var i=0; i<grid_ids.length; i++){
        var rowid = grid_ids[i];
        var aRow = $('#task_table').jqGrid('getRowData',rowid);
        if (taskID == aRow['taskID'])
            return rowid;
    }
    return null;
}

function stopTask (taskID,pid){
    $.ajax({
        url: APPALIAS+'/adminLayer/stopTask/'+taskID+'/'+pid,
        type:'GET',
        dataType: 'json',
        success: function(task){
            alert('La tarea ha sido cancelada.');
            var grid = $('#task_table');
            var taskID = task.taskID;
            var rowID = findRowIDByTaskID(taskID);
            var myDelOptions = {
                // because I use "local" data I don't want to send the changes
                // to the server so I use "processing:true" setting and delete
                // the row manually in onclickSubmit
                onclickSubmit: function(options) {
                    var grid_id = $.jgrid.jqID(grid[0].id),
                    grid_p = grid[0].p,
                    newPage = grid_p.page,
                    rowids = grid_p.multiselect? grid_p.selarrrow: [grid_p.selrow];

                    // reset the value of processing option which could be modified
                    options.processing = true;

                    // delete the row
                    $.each(rowids,function(){
                        grid.delRowData(this);
                    });
                    $.jgrid.hideModal("#delmod"+grid_id,
                    {
                        gb:"#gbox_"+grid_id,
                        jqm:options.jqModal,
                        onClose:options.onClose
                    });

                    if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
                        if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
                            // if after deliting there are no rows on the current page
                            // which is the last page of the grid
                            newPage--; // go to the previous page
                        }
                        // reload grid to make the row from the next page visable.
                        grid.trigger("reloadGrid", [{
                            page:newPage
                        }]);
                    }

                    return true;
                },
                afterShowForm: function ($form) {
                    $("#dData", $form.parent()).click();
                },
                processing:true
            };
            if(rowID) {
                grid.jqGrid('delGridRow', rowID,myDelOptions);
            }            
                        
        } // End of success function of ajax form
    });
}
// al inicio se buscan todas las taréas que están corriendo               
$(document).ready(function() {
    $.ajax({
        url: APPALIAS+'/adminLayer/getRunningTasksForInit',
        type:'GET',
        dataType: 'json',
        success: function(tasks){
                        
            var taskGridData = [];
            $.each(tasks,function(i,task){
                var intervalID = window.setInterval(function(){
                    checkStatus(task.taskID,task.pid,task.layer);
                }, CHECK_STATUS_INTERVAL);
                
                var taskObject = {
                    taskID : task.taskID,
                    pid: task.pid,
                    layer: task.layer,
                    status: TASK_STATUS[task.status],
                    startDate: task.startDate,
                    tilesProcessed: task.tilesProcessed,
                    endDate: task.endDate,
                    //refresh:'<button onclick="checkStatus('+task.taskID+','+task.pid+','+'\''+task.layer+'\''+');">ver estado</button>',
                    stop:'<button onclick="stopTask('+task.taskID+','+task.pid+');">detener</button>',
                    intervalID: intervalID
                };
                taskGridData[i]=taskObject;
            });
            $('#task_table').jqGrid('setGridParam', {
                data: taskGridData
            }).trigger('reloadGrid');
                        
        } // End of success function of ajax form
    });
            
});


function onLayerChange(layer) {
    $.ajax({
        url: APPALIAS+'/adminLayer/getSelectedLayerData/'+layer,
        type:'GET',
        dataType: 'json',
        success: function(data) {
            if (data){
                //actualizo los srs 
                var srsSelect = $('#grid');
                srsSelect.find('option').remove().end();
                var gridsResolutions = data.resolutions;
                $.each(data.grids, function(i, value) {   
                    var gridAttributes = value['@attributes'],
                    restricted_extent = null,
                    minzoom = 0,
                    maxzoom = gridsResolutions[value[0]].length;
                    
                    if (gridAttributes) {
                        restricted_extent = gridAttributes['restricted_extent'];
                        minzoom = gridAttributes['minzoom'] ? gridAttributes['minzoom'] : minzoom;
                        maxzoom = gridAttributes['maxzoom'] ? gridAttributes['maxzoom'] : maxzoom;
                    }
                    srsSelect
                    .append($('<option></option>')
                        .attr('value',value[0])
                        .text(value[0]).attr('minzoom',minzoom)
                        .attr('maxzoom',maxzoom)
                        .attr('restricted_extent',restricted_extent? restricted_extent : '')
                        );
                    
                }); 
                onGridChange($('#grid').children('option:selected'));
            }
                        
        } // End of success function of ajax form
    });
   
} 
function onGridChange(srs) {
    var minZoom = parseInt(srs.attr('minzoom'));
    var maxZoom = parseInt(srs.attr('maxzoom'));
    var minZoomLevelSelector =  $('#minZoomLevel');
    minZoomLevelSelector.find('option').remove().end();
    $('#maxZoomLevel').find('option').remove();
    for (var i = minZoom; i<= maxZoom ; i++  ) {
        minZoomLevelSelector.append($('<option></option>').attr('value',i).text(i));
    }
    fillMaxZoomLevels() ;
    updateSelectRegionURL(srs.val());

}
function fillMaxZoomLevels() {
    var minZoom = $('#minZoomLevel option:selected').val();
    var maxZoom = parseInt($('#grid option:selected').attr('maxzoom'));
    var maxZoomLevelSelector =  $('#maxZoomLevel');
    maxZoomLevelSelector.find('option').remove();
    for (var i = minZoom; i<= maxZoom ; i++)   {
        maxZoomLevelSelector.append($('<option></option>').attr('value',i).text(i));
    }

}
function updateSelectRegionURL(srs) {
    $('#regionSelectAnchor div[srs="'+srs+'"]').show();
    $('#regionSelectAnchor div[srs!="'+srs+'"]').hide();
}
